import { useCallback } from 'react'
import { useSnippetsStore } from '@renderer/stores'
import { template } from '@renderer/utils'

export function useSelect () {
  const snippets = useSnippetsStore(state => state.snippets)
  const activeId = useSnippetsStore(s => s.activeId)
  const setSnippets = useSnippetsStore(state => state.setSnippets)
  const setSearchValue = useSnippetsStore(state => state.setSearchValue)

  const selectItem = useCallback(async (id: number | string) => {
    const item = snippets.find(i => i.id === id)
    if (item) {
      if (item.url) {
        window.api.openExternal(item.url)
      } else {
        await navigator.clipboard.writeText(template.render(item.content))
      }
    }
    setSnippets([])
    setSearchValue('')
    window.api.closeWindow('search')
  }, [snippets])

  return {
    snippets,
    activeId,
    selectItem,
  }
}
